//var BaseUrl = "http://192.168.1.102:8001/";
var BaseUrl = "http://m.niding.net:8000/";
//取querystring
function GetQuery(name)
{
    return window.location.search.match(new RegExp('(?:\\?|&)' + name + '=([^&]*?)(?:&|$)', 'i')) ? RegExp.$1 : '';
}

//ajax-get请求(url, param, callback)
function get(url, param, callback)
{
    Ajax('get', true, url, param, callback, null, null);
}
//ajax-syncpost请求(url, param, callback)
function syncpost(url, param, callback)
{
    Ajax('post', false, url, param, callback, null, null);
}
//ajax-post请求(url, param, callback)
function post(url, param, callback)
{
    Ajax('post', true, url, param, callback, null, null);
}
//ajax-post请求(url, param, callback, loading)
function post(url, param, callback, loading)
{
    Ajax('post', true, url, param, callback, loading, null);
}
//ajax-post请求(url, param, callback, loading,index)
function post(url, param, callback, loading, index)
{
    Ajax('post', true, url, param, callback, loading, index);
}
//ajax请求
function Ajax(type, asynctype, url, param, callback, loading, index)
{

    if (url.indexOf('http;//') <= -1 && url.indexOf('.ashx') <= -1)
        url = "/HttpRoute.ashx?command=" + url;
    $("#" + loading).show();
    $.ajax({
        url: url,
        data: isObject(param) ? JSON.stringify(param) : param,
        type: type,
        cache: false,
        async: asynctype,
        dataType: 'json',
        contentType: "application/json", //必须有
        success: function (data)
        {
            try
            {
                data.data = (data == null || data.data == "") ? "" : JSON.parse(data.data);
                var result = isObject(data) ? data : JSON.parse(data);
                if (data != null&&result.status == 1 && typeof (result.data.islogin) != "undefined" && !result.data.islogin)
                {
                    location.href = "/UserCenter/login.shtml";
                }
                if (isObject(index) || index >= 0)
                    callback(result, index);
                else
                    callback(result);
                $("#" + loading).hide();
                console.log(url + "返回成功！");
            } catch (e)
            {
                console.log(url + "返回成功，但加载数据出现问题！" + e);
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            console.log("加载数据出现问题！");
        }
    });

}

//ajax请求  JSON文件
function DataAjax(url, callback)
{
    $.ajax({
        url: url,
        success: function (result)
        {
            callback(result);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            console.log("加载数据出现问题！");
        }
    });
}
//ajax请求  ashx数据
function commonAjax(data, callback)
{
    $.ajax({
        url: "../Public/CommonAction.ashx",
        async: false,
        data: data,
        type: "post",
        success: function (data)
        {
            callback(data);
        }
    });
}



function parseQueryString()
{
    var str = window.location.search.substr(1);
    if (str === '')
    {
        return {
        };
    }
    var ret = {
    };
    str = str.split('&');
    for (var i = 0, len = str.length; i < len; i++)
    {
        var o = str[i].split('=');
        ret[o[0]] = o[1];
        ret[o[0].toLowerCase()] = o[1];
    }
    return ret;
}
function isObject(source)
{
    return 'function' == typeof source || !!(source && 'object' == typeof source);
};
//取星期几
function GetWeek(date)
{
    var today = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
    var day;
    if (date.indexOf('-') > 0)
        day = new Date(Date.parse(date.replace(/-/g, '/')));
    else
        day = new Date(Date.parse(date));
    var week = today[day.getDay()];
    return week;
}

//倒计时
//方法：Timer(btn,txt, type, time) 
//参数说明  btn:点击按钮(没有传空)
//          txt:绑定文字的控件
//          type: 1：酒店 2:机票  3：旅游   10:发送短信
//          time: 秒
function Timer(btn, txt, type, time, callback)
{
    var intDiff = time;
    //var intDiff = 10;
    var countdown = setInterval(CountDown, 1000);

    function CountDown()
    {
        var minute = 0,
            second = 0;//时间默认值		
        if (intDiff > 0)
        {
            intDiff--;
            minute = Math.floor(intDiff / 60);
            second = Math.floor(intDiff) - (minute * 60);
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            var strTxt = '';
            switch (type)
            {
                case 1:
                    strTxt = '请您在<span class=\"pay_info_lnk2\" style=\"font-size:16px;font-weight:bold\">' + minute + '分' + second + '秒' + '</span>内完成支付。';
                    $(txt).html(strTxt);
                    break;
                case 2:
                    strTxt = '航班价格变动频繁，请您在<span class=\"pay_info_lnk2\" style=\"font-size:16px;font-weight:bold\">' + minute + '分' + second + '秒' + '</span>内完成支付。';
                    $(txt).html(strTxt);
                    break;
                case 3:
                    strTxt = '请您在<em>' + minute + '分' + second + '秒' + '</em>内完成支付。';
                    $(txt).html(strTxt);
                    break;
                case 10:
                    //$(btn).attr("disabled", "disabled").attr("disabled", "disabled").val('重新发送');
                    //$(txt).removeAttr("disabled");
                    //strTxt = second + '秒';
                    //$(txt).val(strTxt);

                    strTxt = second + '秒后重新发送';
                    $(btn).attr("disabled", "disabled").val(strTxt);

                    break;
                case 11:
                    strTxt = '<em>' + second + '秒' + '</em>后自动返回登录页。';
                    $(txt).html(strTxt);
                    break;
                case 12:
                    $(btn).attr("disabled", "disabled").val(second + '秒重新发送');

                    break;
                default:

            }
        }
        else
        {
            clearInterval(countdown);
            switch (type)
            {
                case 1:
                case 2:
                case 3:
                    // alert('时间到了');
                    callback();
                    break;
                case 10:
                    //$(txt).html(time + '秒');
                    //$(btn).removeAttr("disabled");
                    //$(txt).attr("disabled", "disabled");

                    //$(txt).html(time + '秒');
                    $(btn).removeAttr("disabled").val('重新发送');
                    //$(txt).attr("disabled", "disabled");
                    break;
                case 11:
                    $(txt).html(time + '秒');
                    location.href = $("#btn_GotoLogin").attr("href");
                    break;
                default:
            }
        }
    }
}
//金额取小数点后两位
function FormatAmount(num)
{
    return (Number(num)).toFixed(2)
}
//判断是否为空
function isNull(item, msg)
{
    if (item.val().length < 1)
    {
        item.css('border-color', 'red');
        if (msg.length > 0)
        {
            alert(msg);
            item.focus();
        }
        return true;
    } else
    {
        item.css('border-color', '#aaa');
        return false;
    }
}



$(function ()
{
    var General = function ()
    {
        var _self = this;
        //判断用户是否登录
        _self.IsLogin = function ()
        {
            var url = window.location.href.toLowerCase();
            var userinfo = _G.GetCookie("_user");
            if (userinfo != null && url.indexOf("/login.") < 0)
            {
                var myinfo = JSON.parse(userinfo);
                $("#Header_UserInfo").show();
                $("#my_UserName").text(myinfo.username);

                $(" .user-operate .login-user-operate").hover(

                            // 鼠标进入 		
                            function ()
                            {
                                var _self = this;
                                //// 停止卷起事件 		
                                //clearTimeout(mouseout_tid[index]);
                                // 当鼠标进入超过 0.2 秒, 展开菜单, 并记录到线程 ID 中 		
                                //mouseover_tid[index] =
                                if (!$(_self).is(":animated"))
                                {
                                    setTimeout(function ()
                                    {
                                        jQuery(_self).find('.operate-list').slideDown(200);
                                    }, 50);
                                }
                            },
                            // 鼠标离开 			
                            function ()
                            {
                                var _self = this;
                                // 停止展开事件 			
                                //clearTimeout(mouseover_tid[index]);

                                // 当鼠标离开超过 0.2 秒, 卷起菜单, 并记录到线程 ID 中 			
                                //mouseout_tid[index] =
                                if (!$(_self).is(":animated"))
                                {
                                    setTimeout(function ()
                                    {
                                        jQuery(_self).find('.operate-list').slideUp(200);
                                    }, 50);
                                }
                            }
                    );
            }
            else
            {
                $("#Header_UserLogin").show();
                var BackUrl = window.location.href;
                if (BackUrl.toLowerCase().indexOf("login.shtml") < 0)
                {
                    $("#btn_Head_UserLogin").attr("href", "/UserCenter/login.shtml?BackUrl=" + escape(window.location.href));
                }
                else
                {
                    $("#btn_Head_UserLogin").attr("href", BackUrl);
                }
            }
            $(document).on("click", "#btn_Head_UserLogin,#btn_Head_Exit", function ()
            {
                post("base_exitlogin", "", function exitlogin() { });
                //var url = "/UserCenter/login.shtml?BackUrl=" + escape(window.location.href);
                //location.href = url;                    
            });
        }
        _self.Trans = function (container, marginTop, isClearHtml)
        {
            var top = marginTop == undefined ? "50px" : marginTop + "px";
            var clearHtml = isClearHtml == undefined || isClearHtml == true ? true : false;
            if (clearHtml)
            {
                $(container).html("");
            }
            var tl = $("<div/>", {
                id: "_topTransLayer", css: {
                    "text-align": "center", "margin-top": top
                }
            }).appendTo($(container));
            $("<img/>", {
                css: {
                    width: "100px"
                }
            }).attr("src", "../Images/loading.gif").appendTo(tl);
            $("<p/>", { css: { padding: "10px" } }).html("正在加载,请稍候...").appendTo(tl);
            return tl;
        };

        _self.HideTrans = function (container)
        {
            $(container).find("div[id=_topTransLayer]").remove();

        };
        _self.TopTrans = function (tip)
        {
            tip = tip == undefined ? "正在加载,请稍候..." : tip;
            var divBox = $("<div>", {
                id: "_topTransLayer1", css: {
                    position: "fixed", width: "100%", height: "100%", top: "0", left: "0", "background-color": "#000", opacity: "0.5"
                }
            }).appendTo($("body"));
            var tl = $("<div/>", {
                css: { position: "absolute", width: "100px", height: "100px", top: "50%", left: "50%", margin: "-50px 0 0 -50px", background: "url(http://res.niding.net/pc/images/loading.gif) 0 0 no-repeat", "background-size": "contain" }
            }).appendTo(divBox);

            $("<p style='position: absolute;position: absolute;width: 100%;top: 50%;text-align: center;margin-top: 53px;color: #ffffff;' />").html(tip).appendTo(divBox);

            $("html").css({
                "overflow-x": "hidden"
            });
            return tl;
        };
        _self.HideTopTrans = function ()
        {
            $("#_topTransLayer1").remove();
            $("html").css({ "overflow-x": "auto" });
        }
        /* 写 cookie 操作 */
        _self.SetCookie = function (c_name, value, expireTime, dhm)
        {
            var exdate = new Date();
            if (dhm == "d")
            {
                exdate.setDate(exdate.getDate() + parseInt(expireTime, 10));
            }
            else if (dhm == "h")
            {
                exdate.setHours(exdate.getHours() + parseInt(expireTime, 10));
            }
            else if (dhm == "m")
            {
                exdate.setMinutes(exdate.getMinutes() + parseInt(expireTime, 10));
            }
            document.cookie = c_name + "=" + escape(value) + "; path=/; domain=" + window.location.hostname + ((expireTime == null) ? "" : ";expires=" + exdate.toGMTString());
        };

        /* 读 cookie 操作 */
        _self.GetCookie = function (c_name)
        {
            if (document.cookie.length > 0)
            {
                c_start = document.cookie.indexOf(c_name + "=")
                if (c_start != -1)
                {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1)
                    {
                        c_end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return null
        };

        /* 删除 cookie 操作 */
        _self.DeleteCookie = function (c_name)
        {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() - parseInt(3650, 10));
            document.cookie = c_name + "=; path=/; domain=" + window.location.hostname + ";expires=" + exdate.toGMTString();
        };

        //增加天数 dateTemp:时间字符串yyyy-MM-dd  days:要添加的天数
        _self.GetNewDay = function (dateTemp, days)
        {
            var dateTemp = dateTemp.split("-");
            var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]);
            var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
            var rDate = new Date(millSeconds);
            var year = rDate.getFullYear();
            var month = rDate.getMonth() + 1;
            if (month < 10) month = "0" + month;
            var date = rDate.getDate();
            if (date < 10) date = "0" + date;
            return (year + "-" + month + "-" + date);
        };
        //获取地址栏参数
        _self.GetQueryString = function (name)
        {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        };
        //interval ：D表示查询精确到天数的之差,H表示查询精确到小时之差,M表示查询精确到分钟之差,S表示查询精确到秒之差,T表示查询精确到毫秒之差
        _self.DateDiff = function (interval, date1, date2)
        {
            var objInterval = {
                'D': 1000 * 60 * 60 * 24, 'H': 1000 * 60 * 60, 'M': 1000 * 60, 'S': 1000, 'T': 1
            };
            interval = interval.toUpperCase();
            var dt1 = new Date(Date.parse(date1.replace(/-/g, '/')));
            var dt2 = new Date(Date.parse(date2.replace(/-/g, '/')));
            try
            {
                //alert(dt2.getTime() - dt1.getTime());
                //alert(eval_r('objInterval.'+interval));
                //alert((dt2.getTime() - dt1.getTime()) / eval_r('objInterval.'+interval));
                return Math.round((dt1.getTime() - dt2.getTime()) / objInterval[interval]);
            } catch (e)
            {
                return e.message;
            }
        };
        //interval ：D表示查询精确到天数的之和,H表示查询精确到小时之和,M表示查询精确到分钟之和,S表示查询精确到秒之和,T表示查询精确到毫秒之和
        _self.DateAdd = function (interval, date, addValue)
        {
            var objInterval = {
                'D': 1000 * 60 * 60 * 24, 'H': 1000 * 60 * 60, 'M': 1000 * 60 * 60 * 24 * 30, 'S': 1000, 'T': 1
            };
            var dateTemp = date.split("-");
            // var nDate = new Date(dateTemp[1], dateTemp[2], dateTemp[0], "", "", "", "");
            var nDate = new Date(date.replace("-", "/").replace("-", "/"));
            var millSeconds = Math.abs(nDate) + (addValue * objInterval[interval]);
            var rDate = new Date(millSeconds);
            var year = rDate.getFullYear();
            var month = rDate.getMonth() + 1;
            if (month < 10) month = "0" + month;
            var date = rDate.getDate();
            if (date < 10) date = "0" + date;
            return (year + "-" + month + "-" + date);

        };
        //获取当前时间
        _self.CurentTime = function ()
        {
            var now = new Date();
            var year = now.getFullYear();       //年
            var month = now.getMonth() + 1;     //月
            var day = now.getDate();            //日
            var hh = now.getHours();            //时
            var mm = now.getMinutes();          //分
            var ss = now.getSeconds();//秒
            var clock = year + "-";
            if (month < 10)
                clock += "0";
            clock += month + "-";
            if (day < 10)
                clock += "0";
            clock += day + " ";
            if (hh < 10)
                clock += "0";
            clock += hh + ":";
            if (mm < 10) clock += '0';
            clock += mm + ":";
            if (ss < 10) clock += '0';
            clock += ss;
            return (clock);
        };
        //用户登录 （参数为JSON 格式数据）
        _self.UserLogin = function (queryData)
        {
            post("base_login", queryData, BindLoginDate);
            function BindLoginDate(result)
            {
                if (result.status == 1)
                {
                    //var userinfo = result.data;
                    //var myuser = { userid: userinfo.id, username: userinfo.username, cid: userinfo.cid };
                    //_G.DeleteCookie("_user");
                    //_G.SetCookie("_user", JSON.stringify(myuser), 1, "d");
                    return "成功";
                }
                else
                {
                    return result.message;
                }
            }
        };
        //用户登录 （参数为JSON 格式数据）
        _self.UploadImage = function (options)
        {
            var defaults = {
                pop_title: "",//弹窗标题
                pop_width: "670",//弹窗宽度
                pop_height: "470",//弹窗高度
                pop_top: "100",//弹窗位置-距左边
                pop_left: "150",//弹窗位置-距顶部
                cut_width: "200",//裁剪宽度(必填)
                cut_height: "200",//裁剪高度 (必填)                    
                action: "",//上传图片类别(见接口)(必填)
                parameter: "",//参数JSON格式 {'userid':'1000000256'}" (必填)          
                //myReceptionID: "",//保存返回图片路径值的元素编号(必填)
                myCallback: ""//回调函数
            };
            options = $.extend({
            }, defaults, options);
            //window.open("../../Public/PicCut/index.aspx?c=" + options.myReceptionID + "&w=" + options.cut_width + "&h=" + options.cut_height + "&t=&b=" + options.myCallback + "&a=" + options.action + "&p=" + options.parameter + "", options.pop_title, "width=" + options.pop_width + ",height=" + options.pop_height + ",top=" + options.pop_top + ",left=" + options.pop_left + ", toolbar=no, menubar=no, scrollbars=auto, resizable=no, location=no, status=no");
             window.open("../../Public/PicCut/index.aspx?w=" +options.cut_width + "&h=" + options.cut_height + "&t=&b=" + options.myCallback + "&a=" + options.action + "&p=" + options.parameter + "", options.pop_title, "width=" + options.pop_width + ",height=" + options.pop_height + ",top=" + options.pop_top + ",left=" + options.pop_left + ", toolbar=no, menubar=no, scrollbars=auto, resizable=no, location=no, status=no");
        };

    }
    /* 通用函数实例 */
    _G = new General();
    _G.IsLogin();
});
var _G = null;




function formatterDate(date)
{
    var datetime = date.getFullYear()
            + "-"// "年"
            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                    + (date.getMonth() + 1))
            + "-"// "月"
            + (date.getDate() < 10 ? "0" + date.getDate() : date
                        .getDate());
    return datetime;
}


String.prototype.ReplaceAll = function (replaceChar, newReplaceChar)
{
    return this.replace(new RegExp(replaceChar, 'gm'), newReplaceChar);
}

function datecalculate(enddate, startdate)
{
    var s1 = new Date(startdate.replace(/-/g, "/"));
    var s2 = new Date(enddate.replace(/-/g, "/"));
    var days = s2.getTime() - s1.getTime();
    var mDays = parseInt(days / (1000 * 60 * 60 * 24));
    return mDays;
}



